// transFile.c
#include "transFile.h"
#define BUF_SIZE 1024

int transFile(const int netfd, const char *filename)
{
    if (netfd == -1)
    {
        fprintf(stderr, "wrong parameter.\n");
        return -1;
    }
    train_t train;
    int filefd = open(filename, O_RDWR);
    ERROR_CHECK(filefd, -1, "open file");

    // char buf[BUF_SIZE] = { 0 };
    int ret = 0;

    // send filename
    train._length = strlen(filename);
    memcpy(train._buff, filename, strlen(filename));
    ret = send(netfd, &train, sizeof(train_t) + train._length, MSG_NOSIGNAL);
    ERROR_CHECK(ret, -1, "send filename");

    // send filesize
    struct stat st;
    ret = fstat(filefd, &st);
    ERROR_CHECK(ret, -1, "fstat");
    off_t filesize = st.st_size;
    train._length = sizeof(filesize);
    memcpy(train._buff, &filesize, sizeof(filesize));
    ret = send(netfd, &train, sizeof(train) + train._length, MSG_NOSIGNAL);
    ERROR_CHECK(ret, -1, "send filesize");

    // send file
    sendfile(netfd, filefd, NULL, filesize);

    printf("transFile success.\n");

    close(filefd);
    return 0;
}

/* int main(int argc,char* args[]) */
/* { */

/*     return 0; */
/* } */
